# coding: utf-8

from operator import index
from typing import List
from PyQt5 import QtCore
from PyQt5.QtWidgets import (
    QWidget,
    QHBoxLayout,
    QVBoxLayout,
    QStackedWidget,
    QCompleter,
)
from PyQt5.QtCore import Qt, QThreadPool, QThread
from PyQt5.QtGui import QIcon, QPixmap

from qfluentwidgets import (
    CardWidget,
    PushButton,
    LineEdit,
    BodyLabel,
    SmoothScrollArea,
    FlowLayout,
)

from app.components.pageFlipWidget import PageTurningWidget
from app.common.load_resources import LoadResourceThread
from app.common.load_resources import ThreadStartsResourceLoading, ThreadLoadPool
from app.components.resourceCard import ResourceCard

Mod_KEYWORDS = []


# 添加模组关键字为搜索框提供提示
def setKeyWords(name):
    Mod_KEYWORDS.append(name)


""" 模组资源界面搜索框 """


class SearchCard(CardWidget):
    def __init__(self, parent=None):
        super().__init__(parent)

        # 初始化组件
        self.titleLabel = BodyLabel(self)
        self.searchLineEdit = LineEdit(self)
        self.searchButton = PushButton(self)

        self.__initWidget()

    def __initWidget(self):
        self.setEnabled(False)
        # 设置组件
        self.titleLabel.setText(self.tr("SEARCH CARD(temporarily unavailable)"))

        self.searchLineEdit.setPlaceholderText(
            self.tr("what Mod resources do you want to search?")
        )

        self.searchButton.setText(self.tr("Search"))
        self.searchButton.setMaximumWidth(200)

        self.__initLayout()

    def __initLayout(self):
        # 初始化布局
        self.layouts = QVBoxLayout(self)
        self.hBoxLayout = QHBoxLayout()
        self.setLayout(self.layouts)

        self.layouts.addWidget(
            self.titleLabel, 0, Qt.AlignmentFlag.AlignTop | Qt.AlignmentFlag.AlignLeft
        )
        self.layouts.addLayout(self.hBoxLayout)

        self.hBoxLayout.addWidget(self.searchLineEdit)
        self.hBoxLayout.addWidget(self.searchButton)


""" 模组资源界面资源显示区 """


class ModScrollArea(SmoothScrollArea):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.widgets = QWidget(self)

        self.__initWidget()

    def __initWidget(self):
        self.setObjectName("ModScrollArea")
        self.setWidgetResizable(True)
        self.setWidget(self.widgets)
        self.setStyleSheet(
            "#ModScrollArea{" "background:transparent;" "border:none;" "}"
        )

        self.widgets.setObjectName("ModScrollAreaWidget")
        self.widgets.setStyleSheet(
            "#ModScrollAreaWidget{" "background:transparent;" "}"
        )

        self.__initLayout()

    def __initLayout(self):
        self.layouts = FlowLayout(self.widgets)
        self.widgets.setLayout(self.layouts)

    def loadWidget(self, widget: QWidget):
        self.layouts.addWidget(widget)


""" 模组总界面 """


class ModInterface(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.pages = 0

        self.searchCard = SearchCard(self)
        self.flipStackedWidget = QStackedWidget(self)
        self.scrollAreaList: List[ModScrollArea] = []

        self.__initWidget()
        self.__initPage()

    def __initWidget(self):
        self.setObjectName("modInterface")

        self.flipStackedWidget.setObjectName("flipStackedWidget")
        self.flipStackedWidget.setStyleSheet(
            "#flipStackedWidget{" "background:transparent;" "border-radius: 8px;" "}"
        )

        self.__initLayout()

    def __initLayout(self):
        self.layouts = QVBoxLayout(self)
        self.layouts.addWidget(self.searchCard, 0, Qt.AlignmentFlag.AlignTop)
        self.layouts.addWidget(self.flipStackedWidget)

    def __initPage(self):
        self.pageLoad = LoadResourceThread(11, "", "getPage", page=1)
        self.pageLoad.pageNumber.connect(lambda num: self._createFlip(num))

        self.pageLoad.start()

    def __initResources(self):
        self.poolList = []
        for i in range(1, self.pages + 1):
            resourceLoad = None
            modScrollArea = None
            modScrollArea = ModScrollArea(self.flipStackedWidget)
            self.flipStackedWidget.addWidget(modScrollArea)
            self.scrollAreaList.append(modScrollArea)

            resourceLoad = LoadResourceThread(11, "", "getResource", i)
            resourceLoad.pageCardInformation.connect(lambda x: self._loadResourceCard(x))

            self.poolList.append(resourceLoad)
        # for thread in self.poolList:

        #     thread.start()
        threadLoad = ThreadStartsResourceLoading(self.poolList)
        ThreadLoadPool.start(threadLoad)

    def _loadResourceCard(self, resources):
        page = resources["currentPage"]
        try:
            authorDict = {
                "Id": resources["authorId"],
                "Name": resources["authorNickname"],
                "Avatar": resources["authorAvatar"],
            }
        except Exception as e:
            authorDict = {
                "Id": resources["authorId"],
                "Name": "请求作者名时出错",
                "Avatar": "null",
            }
            print(f"请求作者信息时出错 ->\n{e}")

        self.scrollAreaList[page - 1].loadWidget(
            ResourceCard(
                resources["coverImage"],
                resources["resourceTitle"],
                authorDict,
                resources["resourceId"],
                resources["updatedAt"],
                resources["resourceSummary"],
                self.scrollAreaList[page - 1].widgets,
            )
        )
        # 保持关键字更新
        setKeyWords(resources["resourceTitle"])
        self.completer = QCompleter(Mod_KEYWORDS, self.searchCard.searchLineEdit)
        self.completer.setCaseSensitivity(Qt.CaseInsensitive)
        self.completer.setMaxVisibleItems(15)
        self.searchCard.searchLineEdit.setCompleter(self.completer)

    def _createFlip(self, pages):
        self.pages = pages
        self.pageFlip = PageTurningWidget(self, pages)
        self.pageFlip.pageChangeSignal.connect(
            lambda x: self.flipStackedWidget.setCurrentIndex(x - 1)
        )
        self.layouts.addWidget(
            self.pageFlip,
            0,
            Qt.AlignmentFlag.AlignBottom | Qt.AlignmentFlag.AlignHCenter,
        )

        self.__initResources()
